// --- 患者状态常量映射 ---
const STATUS_MAP = {
    IN_TREATMENT: { name: '就诊中', class: 'status-active' },
    NEED_REVIEW: { name: '需复诊', class: 'status-review' },
    FOLLOW_UP: { name: '长期跟进', class: 'status-follow' },
    ARCHIVED: { name: '档案归档', class: 'status-archived' },
  };
  
  /**
   * 封装患者列表的 Mock 数据
   */
  const getPatientListData = () => {
    return [
      { patientId: 'P00123', patientName: '李思涵', initial: '李', gender: '女', age: 25, lastVisitDate: '今天 10:30', status: 'IN_TREATMENT' },
      { patientId: 'P00456', patientName: '张建国', initial: '张', gender: '男', age: 38, lastVisitDate: '2025-11-20', status: 'NEED_REVIEW' },
      { patientId: 'P00789', patientName: '王梓涵', initial: '王', gender: '女', age: 16, lastVisitDate: '2025-10-01', status: 'FOLLOW_UP' },
      { patientId: 'P01011', patientName: '陈敏', initial: '陈', gender: '女', age: 45, lastVisitDate: '2025-09-01', status: 'NEED_REVIEW' },
      { patientId: 'P01122', patientName: '赵薇薇', initial: '赵', gender: '女', age: 31, lastVisitDate: '2025-07-01', status: 'ARCHIVED' },
      { patientId: 'P01334', patientName: '孙明', initial: '孙', gender: '男', age: 55, lastVisitDate: '2025-06-01', status: 'ARCHIVED' },
    ].map(p => ({
      ...p,
      statusName: STATUS_MAP[p.status].name,
      statusClass: STATUS_MAP[p.status].class,
    }));
  };
  
  Page({
    data: {
      allPatientList: [], // 原始完整的列表数据
      filteredList: [],    // 经过搜索和筛选后的列表数据
      currentStatus: 'ALL',// 当前选中的状态 tab (ALL, IN_TREATMENT, etc.)
      searchKeyword: '',   // 当前搜索关键词
      statusTabs: [        // 状态 Tabs 结构
        { key: 'ALL', name: '全部患者', count: 0 },
        { key: 'IN_TREATMENT', name: '就诊中' },
        { key: 'NEED_REVIEW', name: '需复诊' },
        { key: 'FOLLOW_UP', name: '长期跟进' },
      ],
    },
  
    onLoad() {
      this.fetchPatientList();
    },
  
    /**
     * 加载/刷新患者列表数据
     */
    fetchPatientList() {
      // 实际应用中：这里调用后端 API 获取所有患者列表
      const list = getPatientListData();
      
      // 1. 计算每个状态的数量
      const counts = list.reduce((acc, p) => {
          acc[p.status] = (acc[p.status] || 0) + 1;
          return acc;
      }, {});
      
      // 2. 更新 Tabs 数量
      const updatedTabs = this.data.statusTabs.map(tab => {
          if (tab.key === 'ALL') {
              tab.count = list.length;
          } else {
              tab.count = counts[tab.key] || 0;
          }
          return tab;
      });
  
      this.setData({
        allPatientList: list,
        statusTabs: updatedTabs
      }, () => {
          // 数据加载完成后，立即执行一次筛选，确保展示正确的初始列表
          this.filterAndSearch();
      });
    },
  
    /**
     * 模糊搜索输入 (问题 5)
     */
    onSearchInput(e) {
      this.setData({ searchKeyword: e.detail.value }, this.filterAndSearch);
    },
  
    /**
     * 切换状态 Tab (问题 4)
     */
    switchStatusTab(e) {
      const key = e.currentTarget.dataset.key;
      this.setData({ currentStatus: key }, this.filterAndSearch);
    },
  
    /**
     * 核心筛选和搜索逻辑
     */
    filterAndSearch() {
      const keyword = this.data.searchKeyword.toLowerCase();
      const status = this.data.currentStatus;
      
      let result = this.data.allPatientList;
  
      // 1. 按状态筛选
      if (status !== 'ALL') {
          result = result.filter(p => p.status === status);
      }
  
      // 2. 模糊搜索 (问题 5)
      if (keyword) {
          result = result.filter(p => 
              p.patientName.toLowerCase().includes(keyword) || 
              p.patientId.toLowerCase().includes(keyword) || 
              (p.phone && p.phone.includes(keyword)) // 假设 phone 字段存在
          );
      }
  
      this.setData({ filteredList: result });
    },
  
    /**
     * 查看患者详细档案 (问题 2, 3)
     */
    viewPatientProfile(e) {
      const patientId = e.currentTarget.dataset.id;
      // 跳转到新增的患者详情/病例列表页
      wx.navigateTo({
        url: `/pages/doctor/patient-detail/patient-detail?id=${patientId}`
      });
    },
  
    /**
     * 新建患者
     */
    addNewPatient() {
      wx.navigateTo({
        url: '/pages/doctor/patient-register/patient-register' 
      });
    },
  
    /**
     * 排序/高级筛选 (Mock 弹出)
     */
    showSortOptions() {
      wx.showActionSheet({
        itemList: ['按最近就诊时间排序', '按项目类型筛选', '按主治医生筛选'],
        success: () => {
          wx.showToast({ title: '已应用排序/高级筛选', icon: 'none' });
        }
      });
    }
  });